#!/usr/bin/env python3
"""
时区迁移脚本
将所有的datetime.utcnow()替换为timezone_now()
"""
import os
import re
import sys

# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

def update_timezone_imports_and_calls(file_path):
    """更新文件中的时区相关导入和调用"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        original_content = content
        
        # 检查是否已经导入了timezone_utils
        if 'from .timezone_utils import' not in content and 'from services.shared.timezone_utils import' not in content:
            # 添加导入
            if 'from datetime import datetime' in content:
                # 在datetime导入后添加
                content = content.replace(
                    'from datetime import datetime',
                    'from datetime import datetime\nfrom .timezone_utils import now as timezone_now'
                )
            elif 'import datetime' in content:
                # 在datetime导入后添加
                content = re.sub(
                    r'(import datetime\n)',
                    r'\1from .timezone_utils import now as timezone_now\n',
                    content
                )
            elif 'from datetime import' in content:
                # 找到datetime相关导入并添加
                content = re.sub(
                    r'(from datetime import[^\n]+\n)',
                    r'\1from .timezone_utils import now as timezone_now\n',
                    content
                )
        
        # 替换所有的datetime.utcnow()调用
        content = content.replace('datetime.utcnow()', 'timezone_now()')
        content = content.replace('datetime.utcnow', 'timezone_now')
        
        # 如果内容有变化，写回文件
        if content != original_content:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"已更新: {file_path}")
            return True
        else:
            print(f"无需更新: {file_path}")
            return False
            
    except Exception as e:
        print(f"处理文件 {file_path} 时出错: {e}")
        return False

def main():
    """主函数"""
    # 要处理的文件列表
    files_to_update = [
        'services/executor/executor.py',
        'services/scheduler/scheduler.py', 
        'services/shared/database.py',
        'services/shared/models.py',
        'services/shared/utils.py',
        'services/web/api.py',
        'services/web/auth.py',
        'services/web/dashboard.py',
        'system_monitor.py'
    ]
    
    project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    
    updated_count = 0
    for file_rel_path in files_to_update:
        file_path = os.path.join(project_root, file_rel_path)
        if os.path.exists(file_path):
            if update_timezone_imports_and_calls(file_path):
                updated_count += 1
        else:
            print(f"文件不存在: {file_path}")
    
    print(f"\n完成！共更新了 {updated_count} 个文件")

if __name__ == '__main__':
    main()